package com.witmore.neutron.ai.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.PageInfo;
import com.jk.common.response.ResponsePageResult;
import com.witmore.neutron.ai.db.entity.RoleDO;
import com.witmore.neutron.ai.db.entity.RolePermissionDO;
import com.witmore.neutron.ai.db.entity.RoleUserDO;
import com.witmore.neutron.ai.db.mapper.RoleMapper;
import com.witmore.neutron.ai.db.mapper.RolePermissionMapper;
import com.witmore.neutron.ai.db.mapper.RoleUserMapper;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RolePermissionBindParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RoleQueryParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RoleResult;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RoleUserResult;
import com.witmore.neutron.ai.web.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色服务实现类
 * Author: 豆子高
 * Date: 2025/1/2
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<RoleUserResult> getRoleByUserId(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }

        // 查询用户的角色关联信息
        List<RoleUserDO> roleUserList = roleUserMapper.selectList(
                new LambdaQueryWrapper<RoleUserDO>()
                        .eq(RoleUserDO::getUserId, userId)
        );

        if (roleUserList.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取角色ID列表
        List<Long> roleIds = roleUserList.stream()
                .map(RoleUserDO::getRoleId)
                .collect(Collectors.toList());

        // 查询角色详细信息
        List<RoleDO> roleList = roleMapper.selectList(
                new LambdaQueryWrapper<RoleDO>()
                        .in(RoleDO::getId, roleIds)
        );

        // 组装返回结果
        List<RoleUserResult> resultList = new ArrayList<>();
        for (RoleUserDO roleUser : roleUserList) {
            // 找到对应的角色信息
            RoleDO role = roleList.stream()
                    .filter(r -> r.getId().equals(roleUser.getRoleId()))
                    .findFirst()
                    .orElse(null);

            if (role != null) {
                RoleUserResult result = new RoleUserResult();
                BeanUtils.copyProperties(roleUser, result);
                result.setRoleName(role.getRoleName());
                result.setRoleType(role.getRoleType());
                resultList.add(result);
            }
        }

        return resultList;
    }

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }

        List<RoleUserDO> roleUserList = roleUserMapper.selectList(
                new LambdaQueryWrapper<RoleUserDO>()
                        .eq(RoleUserDO::getUserId, userId)
        );

        return roleUserList.stream()
                .map(RoleUserDO::getRoleId)
                .collect(Collectors.toList());
    }

    @Override
    public ResponsePageResult<RoleResult> getRolePage(RoleQueryParam queryParam) {
        // 构建查询条件
        LambdaQueryWrapper<RoleDO> queryWrapper = new LambdaQueryWrapper<RoleDO>()
                .eq(RoleDO::getIsDeleted, (byte) 0)
                .like(StringUtils.hasText(queryParam.getRoleName()),RoleDO::getRoleName, queryParam.getRoleName())
                .eq(queryParam.getRoleType() != null,RoleDO::getRoleType, queryParam.getRoleType())
                .orderByDesc(RoleDO::getCreateTime)
                ;

        // 分页查询
        Page<RoleDO> page = new Page<>(queryParam.getPage(), queryParam.getSize());
        Page<RoleDO> rolePage = roleMapper.selectPage(page, queryWrapper);

        // 如果没有数据，返回空结果
        if (rolePage.getRecords().isEmpty()) {
            return ResponsePageResult.success(new ArrayList<>(),
                    new PageInfo(queryParam.getPage(), queryParam.getSize(), 0L, 0L));
        }

        // 转换为结果对象
        List<RoleResult> roleResults = rolePage.getRecords().stream()
                .map(roleDO -> {
                    RoleResult roleResult = new RoleResult();
                    BeanUtils.copyProperties(roleDO, roleResult);
                    return roleResult;
                })
                .collect(Collectors.toList());

        // 构建分页信息
        PageInfo pageInfo = new PageInfo(queryParam.getPage(), queryParam.getSize(),
                rolePage.getTotal(), rolePage.getPages());

        return ResponsePageResult.success(roleResults, pageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindRolePermissions(RolePermissionBindParam bindParam, String creator) {
        Long roleId = bindParam.getRoleId();
        List<Long> permissionIds = bindParam.getPermissionIds();

        // 先删除该角色已有的权限关联
        LambdaQueryWrapper<RolePermissionDO> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(RolePermissionDO::getRoleId, roleId);
        rolePermissionMapper.delete(deleteWrapper);

        // 如果权限ID列表为空，则只是解绑所有权限
        if (permissionIds == null || permissionIds.isEmpty()) {
            return true;
        }

        // 批量插入新的权限关联
        List<RolePermissionDO> rolePermissionList = permissionIds.stream()
                .map(permissionId -> {
                    RolePermissionDO rolePermission = new RolePermissionDO();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(permissionId);
                    rolePermission.setCreator(creator);
                    rolePermission.setCreateTime(LocalDateTime.now());
                    rolePermission.setUpdateTime(LocalDateTime.now());
                    return rolePermission;
                })
                .toList();

        // 批量插入
        for (RolePermissionDO rolePermission : rolePermissionList) {
            int result = rolePermissionMapper.insert(rolePermission);
            if (result <= 0) {
                throw new RuntimeException("角色权限绑定失败");
            }
        }

        return true;
    }
}
